package com.taokatao.cardmee.business.profile;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.UploadPhotoInfo;
import com.taokatao.cardmee.business.cardcrud.InfoEditActivity;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.common.widget.picker.DatePickerDialog;
import com.taokatao.cardmee.db.UserDao;
import com.taokatao.cardmee.db.model.User;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProfileInfoEditActivity extends BaseActivity implements View.OnClickListener, TitleLayout.Callback {

    @BindView(R.id.l_title) TitleLayout layTitle;

    @BindView(R.id.i_avatar) ImageView iAvatar;
    @BindView(R.id.t_user_tel) TextView tUserTel;
    @BindView(R.id.t_nickname) TextView tNickname;
    @BindView(R.id.t_realname) TextView tRealName;
    @BindView(R.id.l_gender) View lGender;
    @BindView(R.id.t_gender) TextView tGender;
    @BindView(R.id.l_birthday) View lBirthday;
    @BindView(R.id.t_birthday) TextView tBirthday;
    @BindView(R.id.l_nickname) View lNickname;
    @BindView(R.id.l_realname) View lRealname;

    private SheetDialog dlgGender;
    private SheetDialog dlgAvatar;

    private long sBirthday;
    private int sGender;
    private String sLocalAvatar;
    private String sUploadedPhotoUrl;
    private DatePickerDialog dlgBirthday;

    static final int REQUEST_CODE_PROFILE_EDIT_NICKNAME = 1032;
    static final int REQUEST_CODE_PROFILE_EDIT_REALNAME = 1033;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info_edit);
        ButterKnife.bind(this);

        cropAspectX = 1;
        cropAspectY = 1;
        expectedOutputCropWidth = 240;
        expectedOutputCropHeight = (int) (1f * expectedOutputCropWidth * cropAspectY / cropAspectX);

        layTitle.setCallback(this);

        resetUserInfo();
    }

    @Override
    public void onMenuClick(TitleLayout lTitle, String flag) {
        Utils.onMobEvent(ProfileInfoEditActivity.this, "clickSaveOfPersonalCenter");
        String sNickname = tNickname.getText().toString();
        if (TextUtils.isEmpty(sNickname)) {
            Utils.showToast("未填写昵称");
            return;
        }
        if (sLocalAvatar != null && sUploadedPhotoUrl == null) {
            requestUploadAvatar();
        } else {
            requestUpdateUser();
        }
    }

    @Override
    @OnClick({R.id.l_gender, R.id.i_avatar, R.id.l_birthday, R.id.l_nickname, R.id.l_realname})
    public void onClick(View v) {
        if (v == lGender) {
            showGenderDialog();
        } else if (v == iAvatar) {
            showAvatarDialog();
        } else if (v == lBirthday) {
            showBirthdayDialog();
        } else if (v == lNickname) {
            Intent intent = new Intent(this, InfoEditActivity.class);
            intent.putExtra("extra_content", tNickname.getText().toString());
            intent.putExtra("extra_max_length", 20);
            startActivityForResult(intent, REQUEST_CODE_PROFILE_EDIT_NICKNAME);
        } else if (v == lRealname) {
            Intent intent = new Intent(this, InfoEditActivity.class);
            intent.putExtra("extra_content", tRealName.getText().toString());
            intent.putExtra("extra_max_length", 10);
            startActivityForResult(intent, REQUEST_CODE_PROFILE_EDIT_REALNAME);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PROFILE_EDIT_NICKNAME) {
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("result");
                tNickname.setText(result);
            }
        } else if (requestCode == REQUEST_CODE_PROFILE_EDIT_REALNAME) {
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("result");
                tRealName.setText(result);
            }
        }
    }

    private void resetUserInfo() {
        User currUser = App.i().getCurrUser();
        if (currUser != null) {
            tUserTel.setText(currUser.getUserTel());
            if (!TextUtils.isEmpty(currUser.getHeadImgUrl())) {
                Glide.with(this).load(currUser.getHeadImgUrl()).placeholder(R.mipmap.avatar_default)
                        .centerCrop().bitmapTransform(App.i().getCropCircleTransformation()).into(iAvatar);
            }
            tNickname.setText(currUser.getUserName());
            tRealName.setText(currUser.getRealName());
            sGender = currUser.getSex();
            tGender.setText(User.GENDER_MALE == currUser.getSex() ? "男" : "女");
            if (currUser.getBirthday() != null) {
                sBirthday = currUser.getBirthday();
                String tmpBirthday = String.valueOf(sBirthday);
                if (tmpBirthday.length() == 8) {
                    tBirthday.setText(tmpBirthday);
                }
            }
        }
    }

    private void showGenderDialog() {
        if (dlgGender == null) {
            dlgGender = new SheetDialog.Builder(this).setTitle("选择您的性别")
                    .addMenu("男", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            sGender = User.GENDER_MALE;
                            tGender.setText("男");
                        }
                    }).addMenu("女", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            sGender = User.GENDER_FEMALE;
                            tGender.setText("女");
                        }
                    }).create();
        }
        dlgGender.show();
    }

    private void showBirthdayDialog() {
        if (dlgBirthday == null) {
            dlgBirthday = new DatePickerDialog.Builder(this)
                    .setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {
                        @Override
                        public void onDateSelected(int[] dates) {
                            tBirthday.setText(String.valueOf(sBirthday = dates[0] * 10000 + dates[1] * 100 + dates[2]));
                        }
                    }).create();
        }

        String tmpBirthday = tBirthday.getText().toString();
        if (tmpBirthday.length() == 8) {
            dlgBirthday.setCurrSelectedItem(tmpBirthday.substring(0, 4), tmpBirthday.substring(4, 6), tmpBirthday.substring(6, 8));
        }
        dlgBirthday.show();
    }

    private void showAvatarDialog() {
        if (dlgAvatar == null) {
            dlgAvatar = new SheetDialog.Builder(this)
                    .addMenu("拍照", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openCamera();
                        }
                    }).addMenu("从相册选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openPhotos();
                        }
                    }).create();
        }
        dlgAvatar.show();
    }

    @Override
    protected void onPictureQueryOut(String path) {
        super.onPictureQueryOut(path);
        if (!TextUtils.isEmpty(path)) {
            Glide.with(ProfileInfoEditActivity.this).load(new File(sLocalAvatar = path))
                    .centerCrop()
                    .bitmapTransform(App.i().getCropCircleTransformation())
                    .into(iAvatar);
        }
    }

    private void requestUploadAvatar() {
        ApiManager.i().uploadAvatar(this, new File(sLocalAvatar), null, new SubscriberAdapter<RespWrapper<UploadPhotoInfo>>() {
            @Override
            public void onNext(RespWrapper<UploadPhotoInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    sUploadedPhotoUrl = o.decode(UploadPhotoInfo.class).headIconUrl;
                    requestUpdateUser();
                }
            }
        }.showProgress(this));
    }

    private void requestUpdateUser() {
        User user = App.i().getCurrUser();
        if (user == null) return;

        final String sNickname = tNickname.getText().toString();
        final boolean isChangedNickname = !TextUtils.equals(sNickname, user.getUserName());
        final String sRealName = tRealName.getText().toString();
        final boolean isChangedRealName = !TextUtils.equals(sRealName, user.getRealName());
        final boolean isChangedGender = (user.getSex() == null || sGender != user.getSex());
        final boolean isChangedAvatar = !TextUtils.isEmpty(sUploadedPhotoUrl);
        final boolean isChangedBirthday = (user.getBirthday() == null || sBirthday != user.getBirthday());

        if (!isChangedNickname && !isChangedRealName && !isChangedGender && !isChangedAvatar
                && !isChangedBirthday) {
            onBackPressed();
            return;
        }

        ApiManager.i().updateUser(this, App.i().getCurrUser().getUuid(),
                isChangedNickname ? sNickname : "",
                isChangedAvatar ? sUploadedPhotoUrl : "",
                "",
                isChangedRealName ? sRealName : "",
                isChangedBirthday ? sBirthday : 0,
                sGender, 0, new SubscriberAdapter<RespWrapper<RespInfo>>() {
                    @Override
                    public void onNext(RespWrapper<RespInfo> o) {
                        super.onNext(o);
                        if (o.code == C.http.RESULT_CODE_SUCCESS) {
                            User currUser = App.i().getCurrUser();
                            if (isChangedNickname) currUser.setUserName(sNickname);
                            if (isChangedAvatar) currUser.setHeadImgUrl(sUploadedPhotoUrl);
                            if (isChangedRealName) currUser.setRealName(sRealName);
                            if (isChangedBirthday) currUser.setBirthday(sBirthday);
                            currUser.setSex(sGender);
                            UserDao userDao = App.i().getUserDBSession().getUserDao();
                            userDao.insertOrReplaceInTx(currUser);

                            Utils.postMainThreadBusEvent(BusEvent.USER_PROFILE_INFO_CHANGED);
                            finish();
                        }
                    }
                }.showProgress(this));
    }

    @Override
    public void onBackPressed() {
        supportFinishAfterTransition();
    }
}
